﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using CoreShop.Library;
using CoreShop.Model;
using Yitter.IdGenerator;
using Sunny.UI;
using CoreShop.Model.FromBody;
using System.Threading.Tasks;
using CoreShop.App.Payment.SxfPay;
using CoreShop.Services;

namespace CoreShop.App
{
    public partial class frmMobilePay : UIForm
    {
        bool isSendPay = false;

        private List<Control> stateControls = new List<Control>();
        public corecmsfoodorderpayment PaymentModel = new corecmsfoodorderpayment();
        SxfPay sxfPay = new SxfPay(AppConstVars.systemsetup, AppConstVars.payaccount);
        public int QueryTimes = 0;//查询次数
        public frmMobilePay(corecmsfoodorderpayment _PaymentResult)
        {
            PaymentModel = _PaymentResult;
            InitializeComponent();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            txtPayCode.Text = "";
            string msg = $"移动支付手动关闭退出，订单号[{PaymentModel.orderNo}],支付单号[{PaymentModel.paymentCode}],支付金额[{PaymentModel.payAmount}]";
            new corecmsprinttasklogServices().Insert(msg);
            Close();
        }

        private void frmMicroPay_Load(object sender, EventArgs e)
        {
            stateControls.Add(pnl_Data);
            stateControls.Add(pnlTool);
            btn_SendPay.Text = "提交(Enter)";
            this.btn_SendPay.BackgroundImage = null;
            lbl_msg1.Text = "";
            txtAmount.Text = PaymentModel.payAmount.ToString("#0.00");
            txtPayType.Text = EnumHelper.GetDescByValue<GlobalEnumVars.Payment>(PaymentModel.paymentId);
        }

        private void frmMicroPay_Shown(object sender, EventArgs e)
        {
            if (PaymentModel.payCode != "")
            {
                txtPayCode.Text = PaymentModel.payCode;
                btn_SendPay_Click(null, null);
            }
            else { 
            
            }
            txtPayCode.Focus();
        }

        private void otherSetStateControls(bool _Enabled)
        {
            foreach (Control item in stateControls)
            {
                item.Invoke(new MethodInvoker(delegate { item.Enabled = _Enabled; }));
            }
            if (_Enabled)
            {
                btn_SendPay.Text = "提交(Enter)";
                this.btn_SendPay.BackgroundImage = null;
                this.Cursor = Cursors.Default;
                this.Refresh();
                txtPayCode.Focus();
            }
            else {
                btn_SendPay.Text = "";
                this.btn_SendPay.BackgroundImage = Properties.Resources.Loading;
                this.Cursor = Cursors.WaitCursor;
                this.Refresh();
            }            
        }

         
        /// <summary>
        /// 根据付款码自动调整付款方式
        /// </summary>
        private void SetAutoPayType()
        {
            string mPayCode = txtPayCode.Text;
            if (mPayCode.Length < 15) return;
            string mSubStr = mPayCode.Substring(0, 1);
            if (mSubStr == "1")
                PaymentModel.paymentId = (int)GlobalEnumVars.Payment.wechatpay;
            else 
            if (mSubStr == "2")
                PaymentModel.paymentId = (int)GlobalEnumVars.Payment.alipay;
            else 
            if (mSubStr == "6")
                PaymentModel.paymentId = (int)GlobalEnumVars.Payment.unionPay;
        }

        private void frmMicroPay_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (txtPayCode.Text != "")
            {
                e.Cancel = true;
            }
        }

        private void frmMicroPay_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (txtPayCode.TextLength == 18 || txtPayCode.TextLength == 19)
                {
                    e.Handled = true;   //将Handled设置为true，指示已经处理过KeyPress事件
                    btn_SendPay_Click(btn_SendPay, null);
                }
                else
                {
                    lbl_msg1.Text = "错误：输入的支付码无效。";
                    txtPayCode.Clear();
                    if (txtPayCode.Enabled == true) txtPayCode.Focus();
                }
            }
            else if (e.KeyCode == Keys.F4)
            {
                if (btnStopQuery.Visible == true) btnStopQuery_Click(this.btnStopQuery, null);
            }
            else if (e.KeyCode == Keys.F5)
            {
                if (btnQueryAgin.Enabled == true) btnQueryAgin_Click(this.btnQueryAgin, null);
            }
            else if (e.KeyCode == Keys.F6)
            {
                if (btnConfirmPayed.Enabled == true) btnConfirmPayed_Click(this.btnConfirmPayed, null);
            }
        }

        private void panel4_Click(object sender, EventArgs e)
        {
            txtPayCode.Focus();
            txtPayCode.SelectionStart = 0;
            txtPayCode.SelectionLength = 220;
        }

        private void btnQueryAgin_Click(object sender, EventArgs e)
        {
            setConfirmPayed();
            setTastState(2);
            switch (AppConstVars.systemsetup.mobilePayType)
            {
                case (int)GlobalEnumVars.MobilePayType.SXF:
                    A_getQueryAgin_Sxf(PaymentModel.paymentCode);//随行付
                    break;
                default:
                    txt_Msg.Text = "支付参数错误.";
                    break;
            }
        }
        
        private void A_SxfPayTradeQuery(string sBillCode) 
        {
            QueryTimes = 0;
        WaitingStart:
            QueryTimes += 1;
            var tradeResult = sxfPay.tradeQuery(sBillCode);            
            if (tradeResult.isSuccess)
            {
                PaymentModel.responseCode = tradeResult.queryResult.respData.sxfUuid;
                PaymentModel.status = (int)GlobalEnumVars.OrderPayStatus.IsPay;
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
            }
            else
            {
                if (tradeResult.queryResult == null) goto WaitingStart;
                string sTranSts = tradeResult.queryResult.respData.tranSts;
                if ((sTranSts == GlobalEnumVars.SxfTranSts.FAIL.ToString())
                    || (sTranSts == GlobalEnumVars.SxfTranSts.CANCELED.ToString())
                    || (sTranSts == GlobalEnumVars.SxfTranSts.CLOSED.ToString()))
                {
                    UIMessageBox.Show(tradeResult.queryResult.respData.tradeMsg);
                    this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
                }
                else
                {
                    if (QueryTimes > 20)
                        setTastState(3);
                    else
                    {
                        Thread.Sleep(1000);
                        goto WaitingStart;
                    }                        
                }                    
                
                //if ((AppConstVars.isQueryPay) && (isPaying)) goto WaitingStart;
            }                
        }

        private void A_getQueryAgin_Sxf(string sBillCode)
        {
            string msg = "";
            if (this.IsHandleCreated)
                this.Invoke(new Action(() =>
                {
                    this.lbl_msg1.Text = "提示：正在处理,请稍候........";
                    msg = "查询单号[" + sBillCode + "]";
                }));
            //int iLogKinterID = SysFunction.WriteWxPayLog(msg, 0, 0, false);
            try
            {
                //写日志
                try
                {
                    if (this.IsHandleCreated)
                        this.Invoke(new Action(() =>
                        {
                            this.btnStopQuery.Visible = true;
                            this.btnQueryAgin.Visible = false;
                        }));
                    Thread newThread = new Thread(() => A_SxfPayTradeQuery(PaymentModel.paymentCode), 1024 * 512);
                    newThread.Name = String.Format("Thread{0}", PaymentModel.paymentCode);
                    newThread.Start();               
                }
                catch (Exception ex)
                {
                    lbl_msg1.Text = "查询错误：" + ex.Message;
                    txt_Msg.Text = txt_Msg.Text + ";" + lbl_msg1.Text;
                }                
            }
            catch (Exception ex)
            {
                //SysFunction.WriteWxPayLog(lbl_msg1.Text, 1, iLogKinterID, false);  //写日志          
            }
        }
        
        private void btnConfirmPayed_Click(object sender, EventArgs e)
        {
            PaymentModel.responseCode = "0000";
            PaymentModel.status = (int)GlobalEnumVars.OrderPayStatus.IsPay;
            PaymentModel.outcomeType = (int)GlobalEnumVars.PayOutcomeType.Unknown;
            new corecmsprinttasklogServices().Insert($"移动支付手动确认，订单号[{PaymentModel.orderNo}],支付单号[{PaymentModel.paymentCode}]");
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
        }

        private void setConfirmPayed()
        {
            btnConfirmPayed.Enabled = true;
            btnConfirmPayed.Visible = true;
            lbl_msg2.Visible = true;
            label7.Visible = true;
        }

        /// <summary>
        /// 设置状态，1支付提交，2支付查询提交，3停止查询提交
        /// </summary>
        private void setTastState(int type) 
        {
            if (type == 1)
            {
                btnCancel.Enabled = false;
                //btnStopQuery.Visible = false;
                btnStopQuery.Visible = true;
                btnStopQuery.Enabled = true;
                AppConstVars.isQueryPay = true;
                btnQueryAgin.Visible = false;
                btnQueryAgin.Enabled = false;
                btnConfirmPayed.Visible = false;
                btnConfirmPayed.Enabled = false;
                pnl_Data.Enabled = false;
                btn_SendPay.Visible = false;
            }
            else if (type == 2)
            {
                AppConstVars.isQueryPay = true;
                btnStopQuery.Visible = true;
                btnStopQuery.Enabled = true;
                btnQueryAgin.Visible = false;
                btnQueryAgin.Enabled = false;
                btnConfirmPayed.Visible = false;
                btnConfirmPayed.Enabled = false;
                btn_SendPay.Visible = false;
                pnl_Data.Enabled = false;
                btnCancel.Enabled = false;
            }
            else if (type == 3)
            {
                btnStopQuery.Visible = false;
                AppConstVars.isQueryPay = false;
                btnQueryAgin.Visible = true;
                btnQueryAgin.Enabled = true;
                btnConfirmPayed.Visible = true;
                btnConfirmPayed.Enabled = true;
                btn_SendPay.Visible = false;
                pnl_Data.Enabled = false;
                btnCancel.Enabled = true;
            }
        }

        private void btnStopQuery_Click(object sender, EventArgs e)
        {
            string msg = $"移动支付手动停止查询，订单号[{PaymentModel.orderNo}],支付单号[{PaymentModel.paymentCode}],支付金额[{PaymentModel.payAmount}]";
            new corecmsprinttasklogServices().Insert(msg);
            setTastState(3);
        }

        /// <summary>
        /// 随行付
        /// </summary>
        public void A_SetPaySDK_SXF_ThreadPay()
        {
            if (isSendPay == true) return;
            try
            {
                this.Invoke(new Action(async () =>
                {
                    PaymentModel.paymentCode = CommFunc.GetCorpNextId(AppConstVars.sysUser.corpId, YitIdHelper.NextId()).ToString();
                    lbl_msg1.Text = "提示：正在处理,请稍候........";
                    setTastState(1);
                    isSendPay = true;
                    string msg = this.txtPayType.Text + ",单号[" + PaymentModel.paymentCode + "]，支付金额[" + txtAmount.Text + "]";
                    SxfPayResultModel sxfPayResultModel = new SxfPayResultModel();
                    try
                    {
                        sxfPayResultModel = await sxfPay.SetPayment(PaymentModel.paymentCode, txtPayCode.Text, CommFunc.ConvertToDecimal(txtAmount.Text));
                    }
                    catch (Exception ex)
                    {
                        lbl_msg1.Text = "错误：" + ex.Message;
                        txt_Msg.Text = txt_Msg.Text + ";" + lbl_msg1.Text;
                    }

                    if ((sxfPayResultModel != null) && (sxfPayResultModel.code == "0000"))
                    {
                        txtPayCode.Text = "";
                        btnQueryAgin.Enabled = true;
                        btnQueryAgin.Visible = true;

                        if (sxfPayResultModel.respData.tranSts == "SUCCESS")
                        {
                            PaymentModel.responseCode = sxfPayResultModel.respData.sxfUuid;
                            PaymentModel.status = (int)GlobalEnumVars.OrderPayStatus.IsPay;
                            this.DialogResult = System.Windows.Forms.DialogResult.OK;
                        }
                        else
                            btnQueryAgin_Click(null, null);
                    }
                    else
                    {
                        lbl_msg1.Text = "返回失败：" + (sxfPayResultModel.msg).Replace("\0", "");
                        lbl_msg2.Text = "提示：" + (sxfPayResultModel.msg).Replace("\0", "");
                        lbl_msg2.Visible = true;
                        txt_Msg.Text = txt_Msg.Text + ";" + lbl_msg1.Text;
                        txtPayCode.Text = "";
                        txtPayCode.Focus();
                        btnQueryAgin.Enabled = true;
                        btnQueryAgin.Visible = true;
                    }
                }));                
            }
            catch (Exception ex)
            {
                lbl_msg1.Text = "错误：" + ex.Message.Replace("\0", "");
                txt_Msg.Text = txt_Msg.Text + ";" + lbl_msg1.Text;
                txtPayCode.Text = "";
                txtPayCode.Focus();
                btnQueryAgin.Enabled = true;
                btnQueryAgin.Visible = true;
            }
        }

        /// <summary>
        /// 随行付
        /// </summary>
        public void A_SetPaySDK_SXF_Thread()
        {
            try
            {
                ShowWaitForm("正在加载支付方式，请稍候......");
                Task.Factory.StartNew(() =>
                {
                    A_SetPaySDK_SXF_ThreadPay();
                }).TaskDis();
            }
            finally
            {
                HideWaitForm();
            }
        }

        /// <summary>
        /// 随行付
        /// </summary>
        public void A_getQueryAgin_Sxf_Thread(string sBillCode)
        {
            Thread.Sleep(5000);
            A_getQueryAgin_Sxf(sBillCode);
            //btnQueryAgin_Click(null, null);
        }

        private void btn_SendPay_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtPayCode.Text))
            {
                UIMessageBox.Show("请扫描付款条码", "提示：", UIStyle.Green, UIMessageBoxButtons.OK);
                txtPayCode.Focus();
                return;
            }
            SetAutoPayType();//根据付款码自动调整付款方式            
            switch (AppConstVars.systemsetup.mobilePayType)
            {
                case (int)GlobalEnumVars.MobilePayType.SXF:
                    A_SetPaySDK_SXF_Thread();
                    break;
                default:
                    txt_Msg.Text = "支付参数错误.";
                    break;
            }
        }
    }
}
